﻿/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Sockets;
using System.Net;
using EffiProzDB.RowIO;
using EffiProzDB.Lib;

/**
 * Base remote session proxy implementation. Uses instances of Result to
 * transmit and recieve data. This implementation utilises the updated HSQL
 * protocol.
 *
 * @author fredt@users
 * @version 1.8.0
 * @since 1.7.2
 */
namespace EffiProzDB
{
    public class HSQLClientConnection : SessionInterface
    {

        const int BUFFER_SIZE = 0x1000;
        byte[] mainBuffer = new byte[BUFFER_SIZE];
        private bool _isClosed;
        private TcpClient socket;
        protected Stream dataOutput;
        protected Stream dataInput;
        protected RowOutputBinary rowOut;
        protected RowInputBinary rowIn;
        private Result resultOut;
        private int sessionID;

        //
        private bool _isReadOnly = false;
        private bool _isAutoCommit = true;

        //
        protected String host;
        protected int port;
        protected String path;
        protected String database;
        protected bool isTLS;
        protected int databaseID;

        public HSQLClientConnection(String host, int port, String path,
                                    String database, bool isTLS, String user,
                                    String password)
        {

            this.host = host;
            this.port = port;
            this.path = path;
            this.database = database;
            this.isTLS = isTLS;

            initStructures();

            Result login = new Result(ResultConstants.SQLCONNECT);

            login.mainString = user;
            login.subString = password;
            login.subSubString = database;

            initConnection(host, port, isTLS);

            Result resultIn = execute(login);

            if (resultIn.isError())
            {

                /** @todo fredt - review error message */
                throw Trace.error(resultIn);
            }

            sessionID = resultIn.sessionID;
            databaseID = resultIn.databaseID;
        }

        /**
         * resultOut is reused to trasmit all remote calls for session management.
         * Here the structure is preset for sending attributes.
         */
        private void initStructures()
        {

            rowOut = new RowOutputBinary(mainBuffer);
            rowIn = new RowInputBinary(rowOut);
            resultOut = Result.newSessionAttributesResult();

            resultOut.add(new Object[7]);
        }

        protected virtual void initConnection(String host, int port,
                                      bool isTLS)
        {
            openConnection(host, port, isTLS);
        }

        protected void openConnection(String host, int port,
                                      bool isTLS)
        {

            try
            {
                socket = new TcpClient(host,port); // HsqlSocketFactory.getInstance(isTLS).createSocket(host, port);
                //socket.Connect(host, port);
                dataInput = dataOutput = socket.GetStream(); //new NetworkStream(socket);
               // dataInput =  new BufferedStream(new NetworkStream(socket));
            }
            catch (Exception)
            {

                /** @todo fredt - change error to no connetion established */
                throw Trace.error(Trace.SOCKET_ERROR);
            }
        }

        protected void closeConnection()
        {

            try
            {
                if (socket != null)
                {
                    socket.Close();
                }
            }
            catch (Exception) { }

            socket = null;
        }

        public virtual Result execute(Result r)
        {
            lock (this)
            {
                try
                {
                    r.sessionID = sessionID;
                    r.databaseID = databaseID;

                    write(r);

                    return read();
                }
                catch (Exception e)
                {
                    throw Trace.error(Trace.CONNECTION_IS_BROKEN, e.ToString());
                }
            }
        }

        public void close()
        {

            if (_isClosed)
            {
                return;
            }

            _isClosed = true;

            try
            {
                resultOut.setResultType(ResultConstants.SQLDISCONNECT);
                execute(resultOut);
            }
            catch (Exception) { }

            try
            {
                closeConnection();
            }
            catch (Exception) { }
        }

        private Object getAttribute(int id)
        {

            resultOut.setResultType(ResultConstants.GETSESSIONATTR);

            Result ins = execute(resultOut);

            if (ins.isError())
            {
                throw Trace.error(ins);
            }

            return ins.rRoot.data[id];
        }

        private void setAttribute(Object property, int id)
        {

            resultOut.setResultType(ResultConstants.SETSESSIONATTR);
            ArrayUtil.fillArray(resultOut.rRoot.data, null);

            resultOut.rRoot.data[id] = property;

            Result resultIn = execute(resultOut);

            if (resultIn.isError())
            {
                throw Trace.error(resultIn);
            }
        }

        public bool isReadOnly()
        {

            Object info = getAttribute((int)SessionInfoConsts.INFO_CONNECTION_READONLY);

            _isReadOnly = ((bool)info);

            return _isReadOnly;
        }

        public void setReadOnly(bool mode)
        {

            if (mode != _isReadOnly)
            {
                setAttribute(mode ? true
                                  : false, (int)SessionInfoConsts.INFO_CONNECTION_READONLY);

                _isReadOnly = mode;
            }
        }

        public bool isAutoCommit()
        {

            Object info = getAttribute((int)SessionInfoConsts.INFO_AUTOCOMMIT);

            _isAutoCommit = Convert.ToBoolean(info);

            return _isAutoCommit;
        }

        public void setAutoCommit(bool mode)
        {

            if (mode != _isAutoCommit)
            {
                setAttribute(mode ? true
                                  : false, (int)SessionInfoConsts
                                      .INFO_AUTOCOMMIT);

                _isAutoCommit = mode;
            }
        }

        public void setIsolation(int level)
        {
            setAttribute(level,
                         (int)SessionInfoConsts.INFO_ISOLATION);
        }

        public int getIsolation()
        {

            Object info = getAttribute((int)SessionInfoConsts.INFO_ISOLATION);

            return Convert.ToInt32(info);
        }

        public bool isClosed()
        {
            return _isClosed;
        }

        public Session getSession()
        {
            return null;
        }

        public void startPhasedTransaction() { }

        public void prepareCommit()
        {

            resultOut.setResultType(ResultConstants.SQLENDTRAN);

            resultOut.updateCount = ResultConstants.HSQLPREPARECOMMIT;

            resultOut.setMainString("");
            execute(resultOut);
        }

        public void commit()
        {

            resultOut.setResultType(ResultConstants.SQLENDTRAN);

            resultOut.updateCount = ResultConstants.COMMIT;

            resultOut.setMainString("");
            execute(resultOut);
        }

        public void rollback()
        {

            resultOut.setResultType(ResultConstants.SQLENDTRAN);

            resultOut.updateCount = ResultConstants.ROLLBACK;

            resultOut.setMainString("");
            execute(resultOut);
        }

        public int getId()
        {
            return sessionID;
        }

        /**
         * Used by pooled connections to reset the server-side session to a new
         * one. In case of failure, the connection is closed.
         *
         * When the Connection.close() method is called, a pooled connection calls
         * this method instead of HSQLClientConnection.close(). It can then
         * reuse the HSQLClientConnection object with no further initialisation.
         *
         */
        public void resetSession()
        {

            Result login = new Result(ResultConstants.HSQLRESETSESSION);
            Result resultIn = execute(login);

            if (resultIn.isError())
            {
                _isClosed = true;

                closeConnection();

                throw Trace.error(resultIn);
            }

            sessionID = resultIn.sessionID;
            databaseID = resultIn.databaseID;
        }

        protected virtual void write(Result r)
        {
            Result.write(r, rowOut, dataOutput);
        }

        protected virtual Result read()
        {

            Result r = Result.read(rowIn, dataInput);

            rowOut.setBuffer(mainBuffer);
            rowIn.resetRow(mainBuffer.Length);

            return r;
        }
    }
}
